<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/4/29
 * Time: 15:46
 * Mail:87658989@qq.com
 */

namespace app\cron\controller;

use app\api\logic\Gps;
use app\base\service\Beidou;
use app\base\service\Redis;
use think\Db;
use think\Exception;

class Work
{
    /**
     * 司机离线短信提醒 5分钟定时
     */
    public function checkDriver(){
        // 在执行订单或有预约单司机
        // $where['driver_id']   = ['GT',0];
        // $where['order_state'] = ['in','5,6,7,8'];
        // $driverW = Db::name('order')->where($where)->column('driver_id');
        // 获取在班状态司机 遍历最好上传GPS时间 超过5分钟未有上传发短信提醒 超过10分钟发短信提醒 超过15分钟没有订单则强制下线
        $redis   = Redis::getInstance();
        $drivers = $redis->hScanYield('car.driver.4.login','*');
        // work_state 1 3
        $sms = new \app\base\logic\Sms();
        foreach ($drivers as $value){
            $driver = unserialize($value);
            if($driver['work_state']==1 || $driver['work_state']==3){
                $gpsTime    = round($driver['gps_time']/1000,0);
                $updateTime = time() - $gpsTime;
                if($updateTime<=600) continue;  //低于10分钟不提醒
                if($updateTime>1800) continue;//超过半小时不提醒 TODO下线
                // 发送短信提醒
                $data = [
                    'driver'=>$driver['name'],
                    'time'=>round($updateTime/60)
                ];
                $sms->addToList($driver['phone'],$data,'SMS_133976600',2);
            }
        }
    }

    /**
     * 订单异常检测 1分钟
     */
    public function checkOrderException(){
        $redis  = Redis::getInstance();
        $key    = 'check_order_exception';
        $check  = new \app\api\model\Order();
        do{
            $orderNo = $redis->pop($key);
            $oid     = Db::name('order')->where('order_no',$orderNo)->value('order_id');
            if($oid>0){
                $check->checkException($oid);
            }
        }while($redis->lLen($key));
    }

    /**
     * 实时订单异常检测
     */
    public function checkOrderExceptionOnline(){
        $redis  = Redis::getInstance();
        $key    = 'jjcx_exception_list';
        $check  = new \app\api\model\Order();
        do{
            $allot = $redis->redis->rPop($key);
            $data  = json_decode($allot,true);
            if($data['id']>0){
                $check->checkOldException($data['id']);
            }
        }while($redis->redis->lLen($key));
    }

    /**
     * 定时画轨迹 1分钟
     */
    public function drawOrderLine(){
        $redis  = Redis::getInstance();
        $key    = 'order_route';
        $gps    = new Gps();
        do{
            $oid     = $redis->pop($key);
            if(intval($oid)>0){
                $gps->drawOrderLine($oid);
            }
        }while($redis->lLen($key));
    }

    /**
     * 旧轨迹检测 5分钟一次
     * @return int|string
     */
    public function checkOldOrderTrack(){
        $gps    = new Gps();
        $beidou = new Beidou();
        $orders = Db::query("SELECT d.apply_number,a.go_time,a.arrival_time,c.from_lon,c.from_lat,c.to_lon,c.to_lat,p_name,d.tag,e.real_name,a.driver_id,f.license_plate FROM  jjcx_com.order_allot a left join jjcx_com.order_apply_allot b on a.id =b.allot_id left join jjcx_com.order_apply_detail c on b.apply_id = c.apply_id left join jjcx_com.order_apply d on b.apply_id = d.id left join jjcx_com.driver e on a.driver_id = e.id left join jjcx_com.car f on a.car_id = f.id where d.status =2 and length(d.tag)>0 order by d.apply_number desc");
        foreach ($orders as $order){
            $orderNo = $order['apply_number'];
            $name    = 'order/'.$order['apply_number'].'.png';
            if(!file_exists($name)){
                $order['order_id'] = $order['apply_number'];
                $gps->drawOrderLine($order,1);
            }
            $goTime      = strtotime($order['go_time']);
            if(time() - $goTime<60) continue;
            $t1    = time() - 30;
            $t2    = time() + 10;
            $track = $beidou->getTrack($order['license_plate'],$t1,$t2,1);
            $pos   = $track[0];
            if(empty($pos)) continue;
            $ret = $gps->findColor($order['apply_number'],$pos['longitude'],$pos['latitude']);
            if($ret==0){
                $has = Db::name('order_exception')->where('apply_number',$orderNo)->find();
                if(empty($has)){
                    $data = [];
                    $data['apply_number']   = $orderNo;
                    $data['order_text']     = $order['real_name'].'$$'.$order['p_name'];
                    $data['order_id']       = 0;
                    $data['exception_type'] = 8;
                    $data['exception_desc'] = '轨迹偏移';
                    $data['add_time']       = date('Y-m-d H:i:s');
                    Db::name('order_exception')->insert($data);
                }else{
                    $data = [];
                    if(strpos($has['exception_desc'],'轨迹偏移') !==false){
                        // TODO 如果已经存在轨迹异常
                    }else{
                        $data['exception_desc'] = $has['exception_desc'].';轨迹偏移';
                        Db::name('order_exception')->where('apply_number',$orderNo)->update($data);
                    }
                }
            }
        }
    }

    /**
     * 在执行订单轨迹检测 5分钟一次
     * @return int|string
     */
    public function checkOrderTrack(){
        $gps    = new Gps();
        $beiDou = new Beidou();
        $field  = 'gps.order_id,gps.go_time,gps.arrival_time,gps.from_lon,gps.from_lat,gps.to_lon,gps.to_lat,o.car_number';
        try{
            $orders = Db::name('order_gps')->alias('gps')
                ->join('order o','gps.order_id = o.order_id','left')
                ->field($field)
                ->where('order_state',7)
                ->whereNull('go_time')
                ->select();
        }catch (Exception $e){
            $orders = [];
        }
        // 循环判断在执行订单是否偏移
        foreach ($orders as $order){
            $name    = 'order/'.$order['order_id'].'.png';
            if(!file_exists($name)){
                $gps->drawOrderLine($order['order_id']);
            }
            $goTime      = strtotime($order['go_time']);
            if(time() - $goTime<60) continue;
            $t1    = time() - 30;
            $t2    = time() + 10;
            $track = $beiDou->getTrack($order['car_number'],$t1,$t2,1);
            $pos   = $track[0];
            if(empty($pos)) continue;
            $ret = $gps->findColor($order['order_id'],$pos['longitude'],$pos['latitude']);
            if($ret==1) continue;
            // 如果偏移
            $hasException = Db::name('order_exception')->where('order_id',$order['order_id'])->find();
            if(empty($hasException)){
                $data = [];
                $data['order_id']       = $order['order_id'];
                $data['exception_desc'] = '轨迹偏移';
                $data['add_time']       = time();
                Db::name('order_exception')->insert($data);
            }else{
                if(strpos($hasException['exception_desc'],'轨迹偏移') !==false){
                    // TODO 已经存在轨迹异常的处理
                }else{
                    $data = [];
                    $data['exception_desc'] = $hasException['exception_desc'].';轨迹偏移';
                    Db::name('order_exception')->where('order_id',$order['order_id'])->update($data);
                }
            }
        }
    }
}